package com.bookstore.client.user.handler;

import com.bookstore.client.user.service.IUserService;
import com.bookstore.commons.beans.Order;
import com.bookstore.commons.beans.Orderitem;
import com.bookstore.commons.beans.User;
import com.bookstore.utils.IdUtils;
import com.sun.media.sound.ModelStandardIndexedDirector;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * company: www.abc.com
 * Author: Administrator
 * Create Data: 2021/5/8 0008
 */

@Controller
@RequestMapping("/client/user")
public class UserHandler {

    @Autowired
    IUserService userService;

    //用户注册
    @RequestMapping("/register")
    public String register(User user, String checkCode, HttpSession session, HttpServletRequest request){
        //System.out.println("注册用户的信息"+user);
        //System.out.println("校验码"+checkCode);
        //判断检验码是否输入正确
        //工具类产生的校验码保存在Session中的checkcode_session中
        user.setActiveCode(IdUtils.getUUID());
        String checkcode_session = (String) session.getAttribute("checkcode_session");
        if(checkCode.equals(checkcode_session)){
            int rows = userService.addUser(user,request);
            if (rows>0){
                return "redirect:/client/registersuccess.jsp";
            }else {
                request.setAttribute("fail","新用户注册失败请重试！");
                return "/client/register.jsp";
            }
        }else {//校验不正确
            request.setAttribute("check_error","校验码错误，请重新输入！");
            return "/client/register.jsp";
        }
    }


    //用户激活
    @RequestMapping("/activeUser")
    public String activeUser(String activeCode){
        System.out.println("激活码为："+activeCode);
        int rows = userService.activeUser(activeCode);
        if(rows>0){
            return "redirect:/client/activesuccess.jsp";
        }else{
            return "redirect:/client/activeFail.jsp";
        }
    }

    //检测邮箱是否被注册
    @RequestMapping("/findEmail")
    @ResponseBody
    public String findEmail(@Param("email") String email){
        System.out.println("注册的邮箱："+email);

        User user = userService.findEmail(email);
        if(user!=null){
            return "EXIST";
        }else {
            return "OK";
        }
    }

    //点击我的账户跳转
    @RequestMapping("/myAccount")
    public String myAccount(HttpSession session,HttpServletRequest request){
        User login_user = (User) session.getAttribute("login_user");
        if(login_user == null){  //用户未登录，跳转到登录
            login_user = autologin(request);   //如果是自动登录，login_user就不为空
            if(login_user!=null){
                session.setAttribute("login_user",login_user);  //自动登录成功，将用户信息放到session中
                return "/client/myAccount.jsp";
            }
            return "/client/login.jsp";
        }else {  //用户登录了，跳转到我的账户
            return "/client/myAccount.jsp";
        }
    }


    //登录
    @RequestMapping("/login")
    public String login(User user, HttpServletRequest request,String autologin, HttpSession session, String remember, HttpServletResponse response){
        //System.out.println("记住用户名："+remember);   1  null
        //查询用户名密码是否存在

        System.out.println("remember========="+remember);
        System.out.println("autologin========"+autologin);

        User login_user = userService.findUserByLogin(user);
        //autologin自动登录  remember记住用户名
        if(login_user!=null){
            if(login_user.getState() == 1){
                if("1".equals(autologin)){
                    addCookie(autologin,user,request,response);
                }else if ("1".equals(remember)){
                    //记住用户名,存在cookie中
                    addCookie(autologin,user,request,response);
                }
                session.setAttribute("login_user",login_user);//设置session 保存用户信息
                return "/client/myAccount.jsp";
            }else {
                request.setAttribute("login_error","用户未激活，请先激活后再登录！");
                return "/client/login.jsp";
            }
        }else {
            request.setAttribute("login_error","用户名或密码错误！");
            return "/client/login.jsp";
        }
    }

    //用户退出
    @RequestMapping("/logout")
    public String logout(HttpSession session, Model model,HttpServletRequest request,HttpServletResponse response){
        session.removeAttribute("login_user");
        Cookie cookie1 = new Cookie("bookstore_username",null);
        cookie1.setMaxAge(0);
        cookie1.setPath(request.getContextPath()+"/");
        response.addCookie(cookie1);
        Cookie cookie2 = new Cookie("bookstore_password",null);
        cookie2.setMaxAge(0);
        cookie2.setPath(request.getContextPath()+"/");
        response.addCookie(cookie2);
        model.addAttribute("login_error","退出成功,请重新登录！");
        return "/client/login.jsp";
    }

    //向Cookie中保存数据
    private void addCookie(String autologin, User user, HttpServletRequest request, HttpServletResponse response) {
        //保存用户名到cookie
        Cookie cookie1 = new Cookie("bookstore_username",user.getUsername());
        //保存三天
        cookie1.setMaxAge(60*60*24*3);
        //cookie的作用路径  当前项目下
        cookie1.setPath(request.getContextPath()+"/");
        //将cookie响应回客户端
        response.addCookie(cookie1);

        //保存密码到cookie
        if ("1".equals(autologin)){
            Cookie cookie2 = new Cookie("bookstore_password",user.getPassword());
            //保存三天
            cookie2.setMaxAge(60*60*24*3);
            //cookie的作用路径  当前项目下
            cookie2.setPath(request.getContextPath()+"/");
            //将cookie响应回客户端
            response.addCookie(cookie2);
        }
    }

    //自动登录
    private  User autologin(HttpServletRequest request){
        String username = null;
        String password = null;
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie:cookies){
            if("bookstore_username".equals(cookie.getName())){
                username = cookie.getValue();
            }
            if("bookstore_password".equals(cookie.getName())){
                password = cookie.getValue();
            }
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        return userService.findUserByLogin(user);
    }

    //用户信息修改
    @RequestMapping("/modifyUser")
    public String modifyUser(HttpSession session,User user,Model model){
        User login_user = (User) session.getAttribute("login_user");
        user.setId(login_user.getId());
        int rows = userService.modifyUser(user);
        if(rows>0){
            model.addAttribute("login_user","用户信息修改成功，请重新登录！");
            return "/client/login.jsp";
        }else {
            model.addAttribute("fail","用户信息修改失败！");
            return "/client/modifyuserinfo.jsp";
        }
    }

    //订单查询
    @RequestMapping("/findOrderByUser")
    public String findOrderByUser(HttpSession session,Model model){
        User login_user = (User) session.getAttribute("login_user");
        List<Order> orders = userService.findOrderByUser(login_user.getId());
        model.addAttribute("orders",orders);
        return "/client/orderlist.jsp";
    }

    //订单查询中的查看订单信息
    @RequestMapping("/findOrderById")
    public String findOrderById(String id, Model model){
        List<Orderitem> items = userService.findOrderById(id);
        model.addAttribute("items",items);
        return "/client/orderInfo.jsp";
    }


    //删除订单
    @RequestMapping("/removeOrderById")
    public String removeOrderById(String id,String flag){
        userService.removeOrderById(id,flag);
        return "redirect:/client/user/findOrderByUser";
    }
}
